package com.example.controller.sys;

import com.example.common.JwtUtils;
import com.example.common.Message;
import com.example.common.RedisUtils;
import com.example.model.sys.UserMaster;
import com.example.model.vo.TokenVo;
import com.example.service.sys.UserMasterService;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.swing.*;

@RestController
@RequestMapping("/sys/userMaster")
@Slf4j
public class UserMasterController {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisUtils redisUtils;


    /**
     * 刷新token
     * @param request
     * @return
     */
    @PostMapping("/refreshToken")
    public Message refreshToken(HttpServletRequest request) {
        long startTime = System.currentTimeMillis();
        log.info("UserMasterController.refreshToken ,start by startTime ->{}", startTime);
        //从 header中获取前端提交的token
        String token = request.getHeader("token");
        //如果header中没有token,则从参数中获取
        if (ObjectUtils.isEmpty(token)) {
            token = request.getParameter("token");
        }
        //从Spring Security上下文获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //获取身份信息
        UserDetails details = (UserDetails) authentication.getPrincipal();
        //重新生成token
        String reToken = "";
        //验证原来的 token是否合法
        if (jwtUtils.validateToken(token, details)) {

            //生成新的token
            reToken = jwtUtils.refreshToken(token);
        }

        //获取本次token的到期时间,交给前端做判断

        long expireTime = Jwts.parser().setSigningKey(jwtUtils.getSecret()).parseClaimsJws(reToken.replace("jwt_", ""))
                .getBody()
                .getExpiration()
                .getTime();

        //清除原来的token信息
        String oldTokenKey = "token_" + token;
        redisUtils.del(oldTokenKey);
        // 存储新的token
        String newTokenKey = "token_" + reToken;
        redisUtils.set(newTokenKey, reToken, 1800);

        //创建TokenVo对象
        TokenVo tokenVo = new TokenVo(expireTime, reToken);
        log.info("UserMasterController.refreshToken 耗时：{} ms", System.currentTimeMillis() - startTime);

        //返回数据
        return Message.ok("生成token成功", tokenVo);


    }


}
